<template>
  <div class="bg-white rounded-lg shadow-sm overflow-hidden">
    <!-- 在搜索区域添加 Form 组件 -->
    <Form :model="searchForm" :labelWidth="120">
      <div class="p-4 border-b border-gray-200">
        <div class="flex flex-wrap items-center gap-4">
          <div class="p-4 border-b border-gray-200">
          <div class="flex flex-wrap items-center gap-4">
            <div class="flex-1 min-w-[200px]">
              <FormItem label="类型名称">
                <Input v-model="searchForm.name" placeholder="请输入类型名称" />
              </FormItem>
            </div>
            <div class="w-full sm:w-auto">
              <Button type="primary" @click="searchTypes">
                <i class="fa fa-search mr-2"></i>搜索
              </Button>
              <Button @click="resetSearch" class="ml-2">重置</Button>
            </div>
          </div>
        </div>
        </div>
      </div>
    </Form>
    <!-- 搜索和筛选区域 -->
    
    <h1>你好</h1>
    <!-- 表格内容区域 -->
    <div class="overflow-x-auto">
      <Table :columns="columns" :data="typeList" border :loading="isLoading">
        <template #status="{ record }">
          <Switch v-model="record.status" @change="toggleStatus(record)" />
        </template>
        <template #action="{ record }">
          <div class="flex space-x-2">
            <Button type="text" size="small" @click="editType(record)">
              <i class="fa fa-edit text-blue-500"></i> 编辑
            </Button>
            <Button type="text" size="small" @click="deleteType(record)">
              <i class="fa fa-trash text-red-500"></i> 删除
            </Button>
          </div>
          </template>
      </Table>
    </div>

    <!-- 分页区域 -->
    <div class="px-4 py-3 flex items-center justify-between border-t border-gray-200">
      <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
        <div>
          <p class="text-sm text-gray-700">
            显示第 <span class="font-medium">{{ (currentPage - 1) * pageSize + 1 }}</span> 至 <span class="font-medium">{{ Math.min(currentPage * pageSize, total) }}</span> 条，共 <span class="font-medium">{{ total }}</span> 条记录
          </p>
        </div>
        <div>
          <Pagination
            @on-change="handlePageChange"
            @on-page-size-change="handleSizeChange"
            :current="currentPage"
            :page-size="pageSize"
            :total="total"
            show-total
            show-sizer
            :page-sizes="[10, 20, 50, 100]"
            simple />
        </div>
      </div>
    </div>
  </div>

  <!-- 新增/编辑类型模态框 -->
  <Modal v-model="editModalVisible" :title="isEditing ? '编辑类型' : '新增类型'" @on-ok="saveType" @on-cancel="hideEditModal">
    <Form :model="editForm" :rules="editRules">
      <FormItem label="类型名称" prop="name">
        <Input v-model="editForm.name" placeholder="请输入类型名称" />
      </FormItem>
      <FormItem label="类型描述" prop="description">
        <Textarea v-model="editForm.description" rows="4" placeholder="请输入类型描述" />
      </FormItem>
      <FormItem label="状态" prop="status">
        <Switch v-model="editForm.status" />
      </FormItem>
    </Form>
    <template #footer>
      <div class="flex justify-end space-x-3">
        <Button @click="hideEditModal">取消</Button>
        <Button type="primary" @click="saveType">保存</Button>
      </div>
    </template>
  </Modal>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'

import { Message } from 'view-ui-plus';
// API服务
import { typeApi } from '@/api/physicalExaminationApi/physicalExamination'

// 状态管理
const editModalVisible = ref(false)
const isEditing = ref(false)
const isLoading = ref(false)

// 搜索表单
const searchForm = reactive({
  name: ''
})

// 编辑表单
const editForm = reactive({
  id: '',
  name: '',
  description: '',
  status: true
})

// 表单验证规则
const editRules = reactive({
  name: [
    { required: true, message: '请输入类型名称', trigger: 'blur' }
  ]
})

// 分页信息
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 表格列定义
const columns = [
  {
    title: '类型ID',
    key: 'id',
    width: 120
  },
  {
    title: '类型名称',
    key: 'name',
    width: 180
  },
  {
    title: '类型描述',
    key: 'description'
  },
  {
    title: '状态',
    key: 'status',
    width: 80
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
    align: 'center'
  }
]

// 类型列表数据
const typeList = ref([])

// 生命周期钩子
onMounted(() => {
  fetchTypeList()
})

// 获取类型列表
const fetchTypeList = async () => {
  isLoading.value = true
  try {
    const response = await typeApi.getList({
      ...searchForm,
      page: currentPage.value,
      pageSize: pageSize.value
    })
    typeList.value = response.data || []
    total.value = response.total || 0
  } catch (error) {
    Message.error('获取类型列表失败，请稍后再试')
  } finally {
    isLoading.value = false
  }
}

// 搜索类型
const searchTypes = () => {
  currentPage.value = 1
  fetchTypeList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchTypes()
}

// 编辑类型
const editType = (record: any) => {
  isEditing.value = true
  Object.assign(editForm, record)
  editModalVisible.value = true
}

// 删除类型
const deleteType = async (record: any) => {
  const confirmResult = await Message.confirm(
    '确定要删除此类型吗？此操作不可撤销。',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
  
  if (confirmResult === 'confirm') {
    try {
      await typeApi.delete(record.id)
      Message.success('类型删除成功')
      fetchTypeList()
    } catch (error) {
      Message.error('类型删除失败，请稍后再试')
    }
  }
}

// 切换类型状态
const toggleStatus = async (record: any) => {
  try {
    // 正确：调用toggleStatus并传入id和status
    await typeApi.toggleStatus(record.id, record.status);
    Message.success('类型状态更新成功')
  } catch (error) {
    // 回滚状态
    record.status = !record.status
    Message.error('类型状态更新失败，请稍后再试')
  }
}

// 保存类型
const saveType = async () => {
  // 表单验证
  const isValid = await validateForm()
  if (!isValid) return
  
  try {
   if (isEditing.value) {
  // 正确：调用update方法并传入id和data
      await typeApi.update(editForm.id, editForm);
      Message.success('类型更新成功');
    } else {
      // 正确：使用ElMessage
      await typeApi.create(editForm);
      Message.success('类型添加成功');
    }
    
    fetchTypeList()
    hideEditModal()
  } catch (error) {
    Message.error(isEditing.value ? '类型更新失败' : '类型添加失败')
  }
}

// 表单验证
const validateForm = () => {
  return new Promise((resolve) => {
    // 这里应该使用iView的表单验证，示例代码
    resolve(true)
  })
}

// 隐藏编辑模态框
const hideEditModal = () => {
  editModalVisible.value = false
}

// 处理分页变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchTypeList()
}

// 处理每页数量变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchTypeList()
}
</script>

<style scoped>
/* 自定义样式 */
</style>    